package com.hk.commons.utils;

import com.hk.commons.eunms.SysCode;
import com.hk.commons.vo.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseRenderUtils {

    private static Logger logger = LoggerFactory.getLogger(ResponseRenderUtils.class);

    /**
     * response返回未登录
     * 
     */
    public static void renderNoLogin(ServletResponse response) {
        String resultStr = JacksonUtil.toJsonStr(new JsonResult(SysCode.USER_NOT_LOGIN));
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        renderJsonStr(httpResponse, resultStr);
    }

    /**
     * response返回无权限
     * 
     */
    public static void renderNoAuth(ServletResponse response) {
        String resultStr = JacksonUtil.toJsonStr(new JsonResult(SysCode.NO_AUTH));
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        renderJsonStr(httpResponse, resultStr);
    }

    public static void renderJsonStr(HttpServletResponse response, final String jsonStr) {
        try {
            response.setContentType("application/json;charset=UTF-8");
            setNoCache(response); //设置为不缓冲
            PrintWriter out = response.getWriter();
            out.write(jsonStr);
            out.flush();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
    * 设置为不缓冲
    */
    private static void setNoCache(HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
    }
}
